package com.jdbc;

import com.jdbc.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 实现登录功能
 * 1.接收用户输入[用户名、密码];
 * 2.创建数据库连接对象;
 * 3.定义预编译SQL语句;
 *   SELECT id FROM user WHERE username=? AND password=?
 * 4.创建预编译SQL执行对象;
 * 5.执行SQL语句executeQuery()
 * 6.判断查询结果[ResultSet]
 */
public class JdbcLogin {
    public static void main(String[] args) {
        // 1.接收用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();

        // 2.连接并操作数据库
        try {
            //1.创建数据库连接对象
            Connection connection = DbUtil.getConnection();
            //2.执行预编译SQL语句
            String sql = "SELECT id FROM user WHERE username=? AND password=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            //3.获取执行结果
            if (rs.next()){
                System.out.println("登录成功");
            }else{
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}






